/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.qdsg.ysg.doctor.ui.dialog;

import android.app.Dialog;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.DicResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseDialogFragment;

import org.jetbrains.annotations.NotNull;


public class ItemDialog extends BaseDialogFragment {
    private OnItemClickListener mListener;
    private Dialog mDialog;
    private RecyclerView recyclerView;
    AddMedicineAdapter adapter;
    List<DicResponse.Dic> list = new ArrayList<>();
    int type; // 0 频率 5 用药部位 2 前缀 4 后缀  1 用法或者途径（后端学名是途径）
    String siteId;
    private EditText edt_search;
    private boolean isGuoYao;


    public static ItemDialog newInstance(int type, String siteId, Boolean isGuoYao) {
        ItemDialog itemDialog = new ItemDialog();
        Bundle bundle = new Bundle();
        bundle.putInt( "type", type );
        bundle.putString( "siteId", siteId );
        bundle.putBoolean( "isGuoYao", isGuoYao );
        itemDialog.setArguments( bundle );
        return itemDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
    }

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = super.onCreateDialog( savedInstanceState );
        mDialog.setCancelable( true );
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setGravity( Gravity.CENTER );
        }
        return mDialog;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mView = inflater.inflate( R.layout.dialog_item, container, false );
        mView.setMinimumWidth( mScreenWidth );
        assert getArguments() != null;
        type = getArguments().getInt( "type" );
        siteId = getArguments().getString( "siteId" );
        isGuoYao = getArguments().getBoolean( "isGuoYao" );
        edt_search = mView.findViewById( R.id.edt_search );
        LinearLayoutManager manager = new LinearLayoutManager( getActivity() );
        manager.setOrientation( LinearLayoutManager.VERTICAL );
        recyclerView = mView.findViewById( R.id.recyclerView );

        recyclerView.setLayoutManager( manager );
        adapter = new AddMedicineAdapter();
        recyclerView.setAdapter( adapter );
        recyclerView.addItemDecoration( new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw( c, parent, state );
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets( outRect, view, parent, state );
                outRect.bottom = DpUtil.dip2px( getActivity(), 1 );
            }
        } );
        requestData( "" );

        edt_search.setOnEditorActionListener( new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 按下完成按钮，这里和上面imeOptions对应
                    requestData( edt_search.getText().toString() );
                    SoftKeyboardUtil.hideSoftKeyboard( Objects.requireNonNull( getActivity() ) );
                }
                return false;
            }
        } );
        return mView;
    }

    private void requestData(String helpCode) {
        if (isGuoYao) {
            //国药，没有默认药品
            getDicList( helpCode );
        } else {
            if (type == 1 || type == 5) {
                //1途径  5部位
                queryRouteAndSiteById( type + "", siteId, helpCode );
            } else {
                getDicList( helpCode );
            }
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated( view, savedInstanceState );
        getDialog().setCanceledOnTouchOutside( false );
    }

    public interface OnItemClickListener {
        void onItem(String s, String id);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener;
    }


    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();
    }


    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {
        @NotNull
        @Override
        public AddMedicineAdapter.Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            AddMedicineAdapter.Holder myHolder;
            myHolder = new AddMedicineAdapter.Holder( LayoutInflater.from( getActivity() ).inflate( R.layout.item_textview, parent, false ) );
            return myHolder;
        }

        @Override
        public void onBindViewHolder(AddMedicineAdapter.Holder holder, final int position) {
            holder.itemView.setOnClickListener( v -> {
                mListener.onItem( list.get( position ).name, list.get( position ).code );
                dismiss();
            } );
            holder.tv_name.setText( list.get( position ).name );
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            Holder(View itemView) {
                super( itemView );
                tv_name = itemView.findViewById( R.id.text );
            }
        }
    }

    /**
     * 查询药品默认信息（频率和途径）
     *
     * @time 2020/11/23 14:01
     */
    private void queryRouteAndSiteById(String siteType, String siteId, String helpCode) {
        RestProxy.getInstance().queryRouteAndSiteById( siteType, siteId, helpCode, new Observer<DicResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DicResponse dicResponse) {
                try {
                    if (dicResponse != null) {
                        list.clear();
                        if (type == 1) {
                            //途径
                            list.addAll( dicResponse.data );
                        } else if (type == 5) {
                            //用药部位
                            list.addAll( dicResponse.data );
                        }
                        adapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError( getActivity(), e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    private void getDicList(String helpCode) {
        String category = "";
        if (isGuoYao) {
            if (type == 0) {
                category = "ysg_drug_frequency";
            } else if (type == 1) {
                category = "drug_route";
            } else if (type == 5) {
//                category = "drug_part";
                category = "drug_position";
            }
        } else {
            if (type == 0) {
                category = "ysg_drug_frequency";
            }
        }
        if (type == 2) {
            category = "diagnose_prefix";
        } else if (type == 4) {
            category = "diagnose_suffix";
        }

        RestProxy.getInstance().getDicList( helpCode, category, new Observer<DicResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DicResponse dicResponse) {
                list.clear();
                list.addAll( dicResponse.data );
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError( getActivity(), e );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

}
